<template>
  <div>
    <!--搜索框-->
    <div>
      <el-input :id="inputId" v-model="query" placeholder="根据名称或编码查询" style="width: 60%"/>
      <el-button type="primary" size="small" @click="expandAll(false)" style="margin-left: 10px">全部收起</el-button>
    </div>
    <!--ztree-->
    <div :style="treePanelStyle" style="overflow: auto;margin-top: 5px;">
      <ul :id="id" class="ztree"></ul>
    </div>
  </div>
</template>

<script>

import {listAllHangyeWithCache} from "@/api/system/hangye";

export default {
  name: "HangyeTreeRender",
  data() {
    return {
      treePanelStyle: {
        height: (this.height||($('#app').height() - 165))+'px'
      },
      treeObj: null,
      treeNodes: [],
      query: '',
      id: 'tree-' + Math.round(Math.random() * 100000),
      inputId: 'input-' + Math.round(Math.random() * 100000),
    };
  },
  props: {
    height: {
      type: Number
    }
  },
  //组件销毁时注销地区树
  destroyed() {
    $.fn.zTree.destroy(this.id);
  },
  //初始化树
  mounted() {
    let _this = this;
    //行业树
    listAllHangyeWithCache().then(res => {
      this.treeNodes = res.data.map(d => {
        return {
          id: d.id,
          name: d.name,
          code: d.code,
          parentCode: d.parentCode,
          title: d.name + '[' + d.code + ']',
          hyLevel: d.level
        }
      });
      let setting = {
        data: {
          simpleData: {
            enable: true,
            idKey: 'code',
            pIdKey: 'parentCode',
            rootPId: '0'
          },
          key: {
            name: 'title'
          }
        },
        callback: {
          //点击事件,交由父组件监听
          onClick(event, treeId, treeNode) {
            _this.$emit('select', treeNode);
          }
        }
      };
      this.treeObj = $.fn.zTree.init($(`#${this.id}`), setting, this.treeNodes);
      //搜索初始化
      fuzzySearch(this.id, '#' + this.inputId, true, false);
    });
  },
  methods: {
    //true 全展开,false全收起
    expandAll(isExpand) {
      this.treeObj.expandAll(isExpand);
    }
  }
}
</script>

<style scoped>

</style>
